<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Consulting;
use app\common\service\GatewayClientServer;
use app\index\dao\ConsultingDao;
use app\index\service\ConsultingServerCheckService;
use think\facade\Log;

class ConsultingUpdated
{
    private GatewayClientServer $gatewayClientServer;

    public function __construct(GatewayClientServer $gatewayClientServer)
    {
        $this->gatewayClientServer = $gatewayClientServer;
    }

    /**
     * 咨询变动 事件监听处理
     *
     * @return mixed
     */
    public function handle(Consulting $consulting)
    {
        // Log::info(ConsultingUpdated::class);
        // Log::info($consulting->toArray());

        $id = $consulting->id;
        $lawyerId = $consulting->lawyerId;
        $memberId = $consulting->memberId;

        if (is_id($lawyerId) || is_id($memberId)) {

            $consultingData = $this->getConsultingDao()->findOfChat($id)->toArray();

            if (is_id($lawyerId)) {
                $consultingData['chatMemberType'] = 1;
                $data = [
                    'action' => CONSULTING_UPDATE,
                    'data' => $consultingData,
                ];
                $this->gatewayClientServer->sendToUid($lawyerId, json_encode($data));
            }
            if (is_id($memberId)) {
                $consultingData['chatMemberType'] = 0;

                $remind = $this->getConsultingServerCheckService()->read($id);
                foreach ($remind as $k => $value) {
                    $consultingData[$k] = $value;
                }

                $data = [
                    'action' => CONSULTING_UPDATE,
                    'data' => $consultingData,
                ];
                $this->gatewayClientServer->sendToUid($memberId, json_encode($data));

            }
        }

    }

    private function getConsultingDao(): ConsultingDao
    {
        return app(ConsultingDao::class);
    }

    private function getConsultingServerCheckService(): ConsultingServerCheckService
    {
        return app(ConsultingServerCheckService::class);
    }
}
